<template>
  <div class="form-test">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>BaseForm 测试页面</span>
          <el-radio-group v-model="mode" @change="handleModeChange">
            <el-radio-button value="create">创建模式</el-radio-button>
            <el-radio-button value="edit">编辑模式</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <el-alert
        :title="modeTitle"
        :type="mode === 'create' ? 'success' : 'warning'"
        :description="modeDescription"
        :closable="false"
        style="margin-bottom: 20px"
      />

      <base-form
        ref="formRef"
        v-model="formData"
        :form-items="formItems"
        :rules="rules"
        :submit-loading="loading"
        label-width="120px"
        @submit="handleSubmit"
        @change="handleChange"
      >
        <!-- 自定义头像插槽 -->
        <template #avatar="{ formData }">
          <div class="avatar-upload">
            <el-avatar :size="80" :src="formData.avatar || undefined">
              {{ formData.username?.charAt(0)?.toUpperCase() || 'U' }}
            </el-avatar>
            <el-button size="small" style="margin-left: 20px">上传头像</el-button>
          </div>
        </template>

        <!-- 额外内容 -->
        <template #extra>
          <el-alert type="info" :closable="false" style="margin-bottom: 20px">
            <template #title>
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ mode === 'create' ? '请填写完整的用户信息' : '编辑用户信息' }}</span>
                <el-button
                  v-if="mode === 'edit'"
                  type="primary"
                  size="small"
                  link
                  @click="viewFormData"
                >
                  查看表单数据
                </el-button>
              </div>
            </template>
          </el-alert>
        </template>

        <!-- 额外按钮 -->
        <template #buttons>
          <el-button v-if="mode === 'edit'" @click="handleCancel">取消</el-button>
          <el-button @click="handleValidate">验证表单</el-button>
          <el-button @click="handleClearValidate">清除验证</el-button>
        </template>
      </base-form>
    </el-card>

    <!-- 表单数据预览 -->
    <el-card style="margin-top: 20px">
      <template #header>
        <span>表单数据实时预览（v-model 双向绑定）</span>
      </template>
      <el-scrollbar height="400px">
        <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
      </el-scrollbar>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { BaseForm, type BaseFormItem } from '@/components/Form';

// 模式：创建 or 编辑
const mode = ref<'create' | 'edit'>('create');

// 表单引用
const formRef = ref();
const loading = ref(false);

// 操作日志
const logs = ref<Array<{ time: string; message: string; type: string }>>([]);

// 添加日志
const addLog = (message: string, type: string = 'info') => {
  const time = new Date().toLocaleTimeString();
  logs.value.unshift({ time, message, type });
  if (logs.value.length > 50) {
    logs.value.pop();
  }
};

// 创建模式的初始数据（空数据）
const createModeData = {
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  realName: '',
  gender: '',
  birthday: '',
  department: [],
  position: '',
  role: [],
  status: 1,
  description: '',
  avatar: '',
  tags: [],
  priority: 3,
  notifyEmail: true
};

// 编辑模式的初始数据（模拟从后端获取的数据）
const editModeData = {
  username: 'zhangsan',
  email: 'zhangsan@example.com',
  phone: '13800138000',
  password: '123456',
  confirmPassword: '123456',
  realName: '张三',
  gender: 'male',
  birthday: '1990-01-01',
  department: ['tech', 'frontend'],
  position: 'senior',
  role: ['user', 'admin'],
  status: 1,
  description: '这是一个测试用户，用于展示编辑模式的表单数据。',
  avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  tags: ['开发', '前端', 'Vue'],
  priority: 4,
  notifyEmail: true
};

// 表单数据
const formData = ref({ ...createModeData });

// 模式标题
const modeTitle = computed(() => (mode.value === 'create' ? '🆕 创建模式' : '✏️ 编辑模式'));

// 模式描述
const modeDescription = computed(() =>
  mode.value === 'create'
    ? '当前为创建模式，表单为空，用户可以填写新的用户信息'
    : '当前为编辑模式，表单已预填充数据，用户可以修改现有信息'
);

// 表单项配置
const formItems: BaseFormItem[] = [
  {
    type: 'slot',
    label: '头像',
    prop: 'avatar',
    slotName: 'avatar'
  },
  {
    type: 'input',
    label: '用户名',
    prop: 'username',
    placeholder: '请输入用户名',
    required: true,
    maxlength: 20,
    showWordLimit: true,
    tip: '用户名长度为 3-20 个字符，只能包含字母、数字和下划线'
  },
  {
    type: 'input',
    label: '邮箱',
    prop: 'email',
    inputType: 'email',
    placeholder: '请输入邮箱',
    required: true
  },
  {
    type: 'input',
    label: '手机号',
    prop: 'phone',
    inputType: 'tel',
    placeholder: '请输入手机号',
    required: true
  },
  {
    type: 'input',
    label: '密码',
    prop: 'password',
    inputType: 'password',
    placeholder: '请输入密码',
    required: true,
    tip: '密码长度至少 6 位'
  },
  {
    type: 'input',
    label: '确认密码',
    prop: 'confirmPassword',
    inputType: 'password',
    placeholder: '请再次输入密码',
    required: true
  },
  {
    type: 'input',
    label: '真实姓名',
    prop: 'realName',
    placeholder: '请输入真实姓名',
    required: true
  },
  {
    type: 'radio',
    label: '性别',
    prop: 'gender',
    radioType: 'button',
    options: [
      { label: '男', value: 'male' },
      { label: '女', value: 'female' },
      { label: '其他', value: 'other' }
    ]
  },
  {
    type: 'date',
    label: '生日',
    prop: 'birthday',
    dateType: 'date',
    valueFormat: 'YYYY-MM-DD',
    tip: '选择您的出生日期'
  },
  {
    type: 'cascader',
    label: '部门',
    prop: 'department',
    options: [
      {
        value: 'tech',
        label: '技术部',
        children: [
          { value: 'frontend', label: '前端组' },
          { value: 'backend', label: '后端组' },
          { value: 'mobile', label: '移动组' },
          { value: 'test', label: '测试组' }
        ]
      },
      {
        value: 'product',
        label: '产品部',
        children: [
          { value: 'design', label: '设计组' },
          { value: 'pm', label: '产品组' }
        ]
      },
      {
        value: 'operation',
        label: '运营部',
        children: [
          { value: 'marketing', label: '市场组' },
          { value: 'customer', label: '客服组' }
        ]
      }
    ],
    tip: '请选择所属部门'
  },
  {
    type: 'select',
    label: '职位',
    prop: 'position',
    placeholder: '请选择职位',
    options: [
      { label: '初级工程师', value: 'junior' },
      { label: '中级工程师', value: 'middle' },
      { label: '高级工程师', value: 'senior' },
      { label: '技术专家', value: 'expert' },
      { label: '技术经理', value: 'manager' }
    ]
  },
  {
    type: 'checkbox',
    label: '角色',
    prop: 'role',
    checkboxType: 'button',
    options: [
      { label: '普通用户', value: 'user' },
      { label: '管理员', value: 'admin' },
      { label: '超级管理员', value: 'super_admin' }
    ],
    tip: '可多选，至少选择一个角色'
  },
  {
    type: 'select',
    label: '标签',
    prop: 'tags',
    placeholder: '请选择或输入标签',
    multiple: true,
    filterable: true,
    allowCreate: true,
    options: [
      { label: '开发', value: '开发' },
      { label: '设计', value: '设计' },
      { label: '测试', value: '测试' },
      { label: '运维', value: '运维' }
    ],
    tip: '可以选择或自定义标签'
  },
  {
    type: 'rate',
    label: '优先级',
    prop: 'priority',
    max: 5,
    showScore: true,
    tip: '设置用户优先级，1-5星'
  },
  {
    type: 'switch',
    label: '状态',
    prop: 'status',
    activeText: '启用',
    inactiveText: '禁用',
    activeValue: 1,
    inactiveValue: 0
  },
  {
    type: 'switch',
    label: '邮件通知',
    prop: 'notifyEmail',
    activeText: '开启',
    inactiveText: '关闭'
  },
  {
    type: 'textarea',
    label: '描述',
    prop: 'description',
    placeholder: '请输入用户描述',
    rows: 4,
    maxlength: 200,
    showWordLimit: true
  }
];

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: '只能包含字母、数字和下划线',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email' as const, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少 6 位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value !== formData.value.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  role: [
    {
      type: 'array' as const,
      required: true,
      message: '请至少选择一个角色',
      trigger: 'change'
    }
  ]
};

// 切换模式
const handleModeChange = (value: 'create' | 'edit') => {
  const confirmMessage =
    value === 'create'
      ? '切换到创建模式将清空当前表单数据，是否继续？'
      : '切换到编辑模式将加载模拟数据，是否继续？';

  ElMessageBox.confirm(confirmMessage, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (value === 'create') {
        formData.value = { ...createModeData };
        addLog('切换到创建模式，表单已清空', 'success');
      } else {
        formData.value = { ...editModeData };
        addLog('切换到编辑模式，已加载模拟数据', 'warning');
      }
      ElMessage.success(`已切换到${value === 'create' ? '创建' : '编辑'}模式`);
    })
    .catch(() => {
      mode.value = value === 'create' ? 'edit' : 'create';
    });
};

// 监听表单数据变化
watch(
  formData,
  () => {
    // 可以在这里添加自动保存等逻辑
  },
  { deep: true }
);

// 提交表单
const handleSubmit = async (data: any) => {
  console.log('提交数据');
};

// 表单项变化
const handleChange = (prop: string, value: any) => {
  console.log('字段变化:', prop, value);
};

// 取消编辑
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消编辑吗？未保存的修改将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 恢复原始数据
      formData.value = { ...editModeData };
      addLog('已取消编辑，恢复原始数据', 'warning');
      ElMessage.info('已取消编辑');
    })
    .catch(() => {
      // 用户取消
    });
};

// 验证表单
const handleValidate = async () => {
  try {
    await formRef.value.validate();
    addLog('表单验证通过 ✓', 'success');
    ElMessage.success('表单验证通过');
  } catch (error) {
    addLog('表单验证失败 ✗', 'danger');
    ElMessage.error('表单验证失败，请检查必填项');
  }
};

// 清除验证
const handleClearValidate = () => {
  formRef.value.clearValidate();
  addLog('已清除表单验证', 'info');
  ElMessage.info('已清除验证');
};

// 查看表单数据
const viewFormData = () => {
  ElMessageBox.alert(`<pre>${JSON.stringify(formData.value, null, 2)}</pre>`, '当前表单数据', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭'
  });
};

// 页面加载时添加日志
addLog('页面初始化完成，当前为创建模式', 'success');
</script>

<style lang="scss" scoped>
.form-test {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    font-weight: bold;
  }

  .avatar-upload {
    display: flex;
    align-items: center;
  }

  .log-item {
    padding: 8px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
    display: flex;
    align-items: center;
    gap: 10px;

    &:last-child {
      border-bottom: none;
    }

    .log-message {
      color: var(--theme-text-color);
    }
  }
}

.el-card {
  background-color: var(--theme-module-bg);
  border: none;
  color: var(--theme-text-color);

  :deep(.el-card__header) {
    border-bottom: 1px solid var(--theme-border-color);
  }
}

pre {
  background-color: var(--theme-element-bg);
  padding: 15px;
  border-radius: 4px;
  color: var(--theme-text-color);
  font-size: 12px;
  line-height: 1.6;
}
</style>
